package com.qf.commons.core.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.function.Supplier;

/**
 *
 * 在没有被IOC容器管理的类中，手动获取IOC容器中的Bean
 */
public class ApplicationUtils implements ApplicationContextAware, BeanDefinitionRegistryPostProcessor {

    private static ApplicationContext context;

    //用来进行bean的注册
    private static BeanDefinitionRegistry registry;

    //手动获取Bean对象
    public static <T> T getBean(Class<T> cls){
        return context.getBean(cls);
    }

    //手动注册Bean对象
    public static void registerBean(Object bean){
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(bean.getClass(), new Supplier() {
            @Override
            public Object get() {
                return bean;
            }
        });

        registry.registerBeanDefinition(bean.getClass().getSimpleName() + bean.hashCode(), beanDefinitionBuilder.getBeanDefinition());
    }

    /**
     * 该方法 - 会将当前的IOC容器对象，作为参数传递过来
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        ApplicationUtils.registry = registry;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
